import { Request } from 'express';
import { UserRole } from '../types/prisma-types';
import type { User } from './prisma-types';

export type AuthUser = Omit<User, 'password'>;

export interface DecodedToken {
  id: string;
  email: string;
  role: UserRole;
  iat?: number;
  exp?: number;
}

export interface AuthenticatedRequest<T = any> extends Request {
  body: T;
  user?: AuthUser;
}

export interface TokenPayload {
  id: string;
  email: string;
  role: UserRole;
}

export interface TokenResponse {
  token: string;
  expiresIn: number;
}

export interface LoginCredentials {
  email: string;
  password: string;
}

export interface RegisterData {
  email: string;
  password: string;
  name: string;
  role: UserRole;
}

export interface AuthResult {
  user: AuthUser;
  token: string;
}

export interface TokenValidationResult {
  isValid: boolean;
  user?: AuthUser;
  error?: string;
}

type PermissionString = '*' | 'read:*' | 'write:own' | 'manage:students' | 'read:own';

// For role-based access control
export const ROLE_PERMISSIONS: Record<UserRole, PermissionString[]> = {
  [UserRole.ADMIN]: ['*'],
  [UserRole.TEACHER]: ['read:*', 'write:own', 'manage:students'],
  [UserRole.STUDENT]: ['read:own', 'write:own']
};

export type Permission = PermissionString;

export function hasPermission(userRole: UserRole, requiredPermission: Permission): boolean {
  const permissions = ROLE_PERMISSIONS[userRole];
  return permissions.includes('*') || permissions.includes(requiredPermission);
}

export function isAdmin(role: UserRole): boolean {
  return role === UserRole.ADMIN;
}

export function isTeacher(role: UserRole): boolean {
  return role === UserRole.TEACHER;
}

export function isStudent(role: UserRole): boolean {
  return role === UserRole.STUDENT;
}
